
function ProcessRoomListResult (data)
{  
    registerTemplate ("RoomListNormalRow", NormalRow);
    registerTemplate ("RoomListSelectedRow", SelectedRow);
    
	var d=new dgrid();
	d.key="eroomtable";
	d.showall = true; 
	d.editable = true;
	d.selected = Controller.SelectedRoom;
    d.headertransform = function ()
    {
        var htm = '';
        htm += '<div style="margin-bottom:10px">&nbsp;';
        htm += 'Create a new room named: <input id="ipn" class=flat value="">';
        htm += '<input onclick="CreateRoom (document.getElementById(\'ipn\').value)" ';
        htm += ' type=button value="Create">';
        htm += '</div>';
        return htm; 
    }
    d.transform = function (row)
    {
        var ok=parseInt(this.selected)==parseInt(row['ID']); 
        var object = { 'template' : ok ? 'RoomListSelectedRow' : 'RoomListNormalRow', 
                        'shortname' : row['Name'].substr(0,40) + (row['Name'].length>40?'...':''), 
                        'gridid' : this.id } 
        if (ok) object.RoomDropdown = RoomDropdown (0, row['RoomFk'], ''); 
        for (var x in row) object[x]=row[x];
        return  Factory.write (object); 
    }
	d.select = function (i)
	{ 
	    Controller.SelectedRoom = i;
	    Controller.Reload ('dceroomtable'); 
	} 
	d.columns = new Array ('Name','Capacity','Comments','Events');
	d.cellpadding= 2; 
	d.rows = RoomEditGrid (0, '');
    return d.draw(); 
}


 
function RoomEditGrid (parentfk, indent)
{
	 var row;
	 var tmp='';
	 var htm=new Array();
	 for (var x in window.rooms)
	 {
		 if (window.rooms[x]['RoomFk']==parentfk)
		 {  
		    row = {
		        'ID' : window.rooms[x]['ID'],
		        'RoomName' : window.rooms[x]['RoomName'],
		        'RoomFk' : window.rooms[x]['RoomFk'],
		        'Name' : indent + window.rooms[x]['RoomName'],
		        'Capacity' : window.rooms[x]['MaxOccupants'],
		        'Events' : window.rooms[x]['EventCount'],
		        'Directions' : window.rooms[x]['Directions']||'',
		        'MapLocation' : window.rooms[x]['MapLocation']||'',
		        'Comments' : window.rooms[x]['Comments']||'',
		        'indent' : indent
		        };
    
			 htm.push (row);
			 
			 tmp = RoomEditGrid (window.rooms[x]['ID'], indent + '....');
			 for (var m in tmp) htm.push (tmp[m]); 
		 }
	 }
	 
	 return htm;
}

 
 function RoomObject (n,v)
 {
	 this.name=n;
	 this.value=v; 
 } 

function RoomCheckListSelect (index,selected)
{    
	var td = document.getElementById ('rcl'+index+''); 
	var lb = document.getElementById ('rcb'+index+'');
	var rm = window.rooms[index];
	td.bgColor = selected ? '#F0F0F0' : 'white'; 
	lb.style.fontWeight = selected ? 'bold' : 'normal';
	
	if (window.currentevent)
	{
	    if (selected) window.currentevent.AddRoom (rm['RoomName'],rm['ID']);
	    else window.currentevent.RemoveRoom (rm['ID']);
	}
	
	UpdateRoomNames ();
} 
 

function FindRoomsInCheckListByName ()
{    
    var row, key, name, value = document.getElementById ('rmf').value;   
    for (var x in window.rooms)
    {
        name = window.rooms[x]['RoomName'].toLowerCase();
        key  = 'rcl'+x;
        row  = document.getElementById (key)
        if (row) row.style.display = name.indexOf (value) >= 0 ? 'inline' : 'none'
    }
} 
 

function LoadRoomCheckList ()
{       
	var string = ','; 
	if (window.currentevent)
	{
	    for (var x in window.currentevent.Rooms)
	    {
		    string += window.currentevent.Rooms[x].value + ','; 
	    }
	}
    var checklist=RoomCheckList (0, string, '');
	var roomselect=document.getElementById ('droomselect');   
	var htm='<div style="padding:2px;background-color:#f0f0f0">Find: <input onkeyup="FindRoomsInCheckListByName()" class=flat id=rmf size=8></div>';
	htm+='<table cellspacing=0 cellpadding=2 width="100%">';
	htm+=checklist
	htm+='</table>'
	roomselect.innerHTML = htm;
	UpdateRoomNames ();
}
 
function GetRoomName (i)
{
	for (var x in window.rooms)
	{
		if (window.rooms[x]['ID']==i) return window.rooms[x]['RoomName']; 
	}
	return 'Room '+i+' was not found';
}
 
function UpdateRoomNames ()
{
	var roominput=document.getElementById ('iRoomName');  
	if (roominput && window.currentevent) roominput.value = window.currentevent.MakeRoomString(); 
	window.resizer.invoke();
}

 
RoomObject.empty = function (name, fk)
{ 
    return { 'ID' : 0,
            'RoomName' : name,
            'Directions' : '',
            'MapLocation' : '',
            'Comments' : '',
            'RoomFk' : fk,
            'MaxOccupants' : 0 
            };
} 
 
RoomObject.Serialize = function (row)
{
    var htm='';
	htm+='<saveroom>\n'; 
    htm+='  <r>\n';
    for (var i in row)
    {
        if (i!='EventCount') htm+='   <f n="'+i+'"><![CDATA[' + row[i] + ']]></f>\n'; 
    }
    htm+='  </r>\n';   
	htm+='</saveroom>\n'; 
	return htm; 
}
 

function SaveRoom ()
{
	var room={}, error=[];
    for (var pt in window.rooms)
    {
        if (window.rooms[pt]['ID'] == Controller.SelectedRoom)
        {    
          	room['ID']			= Controller.SelectedRoom; 
          	room['RoomName']	= getElementValue('iRoomName'); 
            room['Directions']	= getElementValue('iDirections'); 
            room['MapLocation']	= getElementValue('iMapLocation'); 
            room['Comments']	= getElementValue('iComments'); 
            room['RoomFk']		= getElementValue('iRoomFk'); 
            room['MaxOccupants']= getElementValue('iMaxOccupants'); 
             
			if (room['RoomFk']==null || typeof (room['RoomFk'])=='undefined' || room['RoomFk']=='')
				error.push ('The room has no parent');
             
			if (room['RoomName']==null || typeof (room['RoomName'])=='undefined' || room['RoomName']=='')
				error.push ('The room has no name');
			 
			if (room['RoomFk']==room['ID'])
				error.push ('The room will <b>disappear</b> if it is made a parent of itself!');
			
			if (error.length > 0)
			{
				alert ("<b>Unable to save '" + room.RoomName + "' because errors were found validating the room:</b>" + 
					   "<hr noshade size=1><font color=firebrick>" + 
					   error.join ("<br>") + 
					   "</font>"); 
				return false;
			}
			window.rooms[pt]['ID'] = room;
			
            var xml = RoomObject.Serialize (room); 
            
            
            var RequestParams = {  
                'aftersend' : ReLoadGlobalRoomsList ,
                'message' : 'Receiving save response...',
                'method' : 'POST',
                'postdata' : xml
                      }; 
            window.request.create (RequestParams);  
               
            break;
        }
    }  
}

 
function RoomDropdown (parentfk, selected, indent)
{
    var ok,htm='',kid=[];
    for (var x in window.rooms)
    {
        if (window.rooms[x]['RoomFk']==parentfk)
        { 
            ok=parseInt(selected, 10)==parseInt(window.rooms[x]['ID'], 10);
            htm += '<option value="'+window.rooms[x]['ID']+'" '+(ok?'selected':'')+'>'
            htm += indent + ''
            htm += '' + window.rooms[x]['RoomName'].substr(0,40) + (window.rooms[x]['RoomName'].length>40?'...':'');// + '/' + selected + '/' + window.rooms[x]['ID'] + '/' + ok;
            htm += '</option>' 
			kid.push (x);
            htm += RoomDropdown (window.rooms[x]['ID'], selected, indent + '....');
        }
    } 
	
    return htm;
}
 
 
function RoomCheckList (parentfk, selected, indent)
{
    var htm='';
    for (var x in window.rooms)
    {
        if (window.rooms[x]['RoomFk']==parentfk)
        {
            ok=selected.indexOf (',' + window.rooms[x]['ID'] + ',')>=0;
			css='background-color:'+(ok?'#FFFF00':'white')+';';
            htm += '<tr><td id="rcl'+x+'" bgcolor="'+(ok?'#FFFF00':'white')+'" '
            htm += ' nowrap style="font-size:8pt;'+css+'" class="datarow">';
            htm += indent + '';
            htm += '<input value="'+window.rooms[x]['ID']+'" ' + (ok?' checked ':'') + ''
            htm += ' id="rck'+x+'" name=rck type="checkbox" onclick="RoomCheckListSelect('+x+',this.checked)">'
            htm += '<label for="rck'+x+'" id="rcb'+x+'" style="'+css+'font-weight:'+(ok?'bold':'normal')+'">'
            htm += '' + window.rooms[x]['RoomName'] + ''
            htm += '</label>'
            htm += '<br>'
            htm += '</td></tr>';
            htm += RoomCheckList (window.rooms[x]['ID'], selected, indent + '....');
        }
    }
    return htm;
}
 
function CLLaunchRoomListDialog()
{
	this.CLLaunchRoomListDialogEx =  LaunchRoomListDialog;
	this.CLLaunchRoomListDialogEx ('UploadCloneDateList');
}

function LaunchRoomListDialog (command)
{   
    var TmpRooms = ',', onc=command||'UpdateEventRoomList';
    for (var x in this.target)
    { 
       if (this.target[x].roomfk) TmpRooms += this.target[x].roomfk + ','
    }
 
    var htm = '';
    htm += '<html>';
    htm += '  <link rel="stylesheet" href="' + LOCATION_PATH_NAME + '/style.css"/>';
    htm += '  <' + 'script language="javascript">\n';
    htm += '  function RoomCheckListSelect() { } \n';
    htm += '  function SaveRooms () {\n';
    htm += '    var ck=document.getElementsByTagName ("INPUT"), ar=[];\n';
    htm += '    for (var x=0;x<ck.length;x++) {\n';
    htm += '      if (ck[x].checked) ar.push (ck[x].value)\n';
    htm += '    }\n';
    htm += '    opener.' + onc + ' ("' + this.params['id'] + '", ar.join(","));\n'; 
    htm += '    self.close();';
    htm += '  }\n';
    htm += '  <' + '/script>';
    htm += '  <body bgcolor="#f0f0f0" style="border:solid 1px #f0f0f0;padding:2px">';
    htm += '    <div style="height:300px;overflow:auto;border:solid 1px #666;background-color:#fff">';   
    htm += RoomCheckList (0, TmpRooms, '');
    htm += '    </div>';
    htm += '    <input type=button value="Change Room(s)" onclick="SaveRooms()">';
    htm += '    <input type=button value="Cancel" onclick="self.close()">';
    htm += '  </body>';
    htm += '</html>';
    var x=window.open ('about:blank',null,'width=350,height=350');
    x.document.write (htm);
}


var NormalRow = ''; 
NormalRow += '<tr>'; 
NormalRow += '<td nowrap class=datarow bgcolor="white">'; 
NormalRow += '<input type="checkbox">'; 
NormalRow += '<a href="./#view/roomlist/id/(ID)">(shortname)</a>'; 
//NormalRow += '<a href="javascript:void(0)" onclick="window.datagrids[(gridid)].select ((ID))">(shortname)</a>'; 
NormalRow += '</td>'; 
NormalRow += '<td nowrap class=datarow bgcolor="white">(Capacity)</td>'; 
NormalRow += '<td nowrap class=datarow bgcolor="white">(Comments)</td>'; 
NormalRow += '<td nowrap width="100%" class=datarow bgcolor="white"><a href="javascript:void(0)" onclick="SearchEventsByRoom ((ID))">(Events)</a></td>';
NormalRow += '</tr>';



var SelectedRow = ''; 
SelectedRow += '<tr>';  
SelectedRow += '<td nowrap class=datarow bgcolor="#f0f0f0" style="color:gray">Name</td>'; 
SelectedRow += '<td nowrap class=datarow bgcolor="#f0f0f0" style="color:gray">Capacity</td>'; 
SelectedRow += '<td nowrap class=datarow bgcolor="#f0f0f0" style="color:gray">Comments</td>';  
SelectedRow += '<td nowrap class=datarow bgcolor="#f0f0f0" style="color:gray">Events</td>'; 
SelectedRow += '</tr>';   
SelectedRow += '<tr>'; 
SelectedRow += '<td nowrap class=datarow bgcolor="aliceblue">'; 
SelectedRow += '<!--<input type="checkbox">-->(ID)&#187;(RoomFk)'; 
SelectedRow += '(indent)<input class=flat id="iRoomName" size=30 value="(RoomName)">';   
SelectedRow += '</td>'; 
SelectedRow += '<td nowrap class=datarow bgcolor="aliceblue">'; 
SelectedRow += '<input class=flat id="iMaxOccupants" size=3 value="(Capacity)">';   
SelectedRow += '</td>'; 
SelectedRow += '<td nowrap class=datarow bgcolor="aliceblue">'; 
SelectedRow += '<input class=flat id="iComments" size=50 value="(Comments)">';   
SelectedRow += '</td>'; 
SelectedRow += '<td nowrap width="100%" class=datarow bgcolor="aliceblue">'; 
SelectedRow += '<a href="javascript:void(0)" onclick="SearchEventsByRoom ((ID))">(Events)</a></td>';        
SelectedRow += '</tr>';
SelectedRow += ''; 
SelectedRow += '<tr>';
SelectedRow += '<td nowrap class=datarow bgcolor="#f0f0f0" style="color:gray">Directions</td>';
SelectedRow += '<td nowrap class=datarow bgcolor="#f0f0f0" style="color:gray">Map Location</td>'; 
SelectedRow += '<td nowrap class=datarow bgcolor="#f0f0f0" style="color:gray">Parent Room</td>'; 
SelectedRow += '<td nowrap class=datarow bgcolor="#f0f0f0" style="color:gray">&nbsp;</td>';  
SelectedRow += '</tr>';
SelectedRow += '<tr>';
SelectedRow += '<td nowrap class=datarow bgcolor="aliceblue"><input class=flat id="iDirections" size=40 value="(Directions)"></td>';
SelectedRow += '<td nowrap class=datarow bgcolor="aliceblue"><input class=flat size=15 id="iMapLocation" value="(MapLocation)"></td>'; 
SelectedRow += '<td nowrap class=datarow bgcolor="aliceblue" colspan="2"><select id="iRoomFk"><option value=0>None(RoomDropdown)</select>'; 
//SelectedRow += '</td><td nowrap class=datarow bgcolor="aliceblue">'; 
SelectedRow += ''; 
SelectedRow += '<input type=button value="Save" onclick="SaveRoom ()">'; 
SelectedRow += '<input type=button (enabled) value="Delete" onclick="DeleteRoom((ID));">'; 
SelectedRow += '<input type=button value="Cancel" onclick="Controller.SelectedRoom = -1;Controller.Reload ();">'; 
SelectedRow += ''; 
SelectedRow += '</td>';  
SelectedRow += '</tr>';
